package utils;


import com.ctrip.framework.apollo.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Slf4j
public class CompressUtil {

    private static final int BUFFER_SIZE = 1024 * 100;

    private CompressUtil() {
    }

    public static void main(String[] args) throws Exception {

        String tarName = "tmp_0.tar.gz";
        String fileName = "tmp_3.csv";

        String currentDir = System.getProperty("user.dir");
        String baseCsvDir = ConfigService.getAppConfig().getProperty(ApolloUtils.BASECSVDIR, ApolloUtils.BASECSVDIR_DEFAULT);
        String baseTarDir = ConfigService.getAppConfig().getProperty(ApolloUtils.BASETARDIR, ApolloUtils.BASETARDIR_DEFAULT);
        String tarFilePath = currentDir + "/" + baseTarDir + tarName;
        // tar目录
        CompressUtil.createDirectory(currentDir + baseTarDir, null);

        String outputDir = currentDir + "/" + baseCsvDir + fileName.split("\\.")[0];
        //csv目录
        CompressUtil.createDirectory(outputDir, null);

        String csvFilePath = outputDir + "/" + fileName;
        // 解压文件
//        boolean flag = CompressUtil.decompress(tarFilePath, outputDir, csvFilePath);
//        System.out.println(flag);
        // 读取文件
        ArrayList<String> list = CSVToList(csvFilePath);
        System.out.println(list);
    }

    public static boolean decompress(String filePath, String outputDir, String csvFilePath) {
        log.info("filePath:{} decompress to csvFilePath:{}", filePath, csvFilePath);
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        try {
            if (!deleteDirectory(outputDir)) {
                log.info("deleteDirectory failed:{} ", outputDir);
                return false;
            }

            if (filePath.endsWith(".zip")) {
                unZip(file, outputDir);
            }
            if (filePath.endsWith(".tar.gz") || filePath.endsWith(".tgz")) {
                decompressTarGz(file, outputDir);
            }
            boolean renameFlag = filterFile(new File(outputDir), csvFilePath);
            boolean deleteFlag = deleteFile(filePath);
            return renameFlag & deleteFlag;
        } catch (IOException e) {
            log.error("decompress error ", e);
        }
        return false;
    }

    /**
     * 解压 .zip 文件
     *
     * @param file      要解压的zip文件对象
     * @param outputDir 要解压到某个指定的目录下
     * @throws IOException
     */
    public static void unZip(File file, String outputDir) throws IOException {
        try (ZipFile zipFile = new ZipFile(file, StandardCharsets.UTF_8)) {
            //创建输出目录
            createDirectory(outputDir, null);
            Enumeration<?> enums = zipFile.entries();
            while (enums.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) enums.nextElement();
                if (entry.isDirectory()) {
                    //创建空目录
                    createDirectory(outputDir, entry.getName());
                } else {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        try (OutputStream out = Files.newOutputStream(new File(outputDir + File.separator + entry.getName()).toPath())) {
                            writeFile(in, out);
                        }
                    }
                }
            }
        }
    }

    public static void decompressTarGz(File file, String outputDir) throws IOException {
        try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(
                        new BufferedInputStream(
                                Files.newInputStream(file.toPath()))))) {
            //创建输出目录
            createDirectory(outputDir, null);
            TarArchiveEntry entry = null;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                //如果是目录
                if (entry.isDirectory()) {
                    //创建空目录
                    createDirectory(outputDir, entry.getName());
                } else {
                    //如果是文件
                    try (OutputStream out = Files.newOutputStream(new File(outputDir + File.separator + entry.getName()).toPath())) {
                        writeFile(tarIn, out);
                    }
                }
            }
        }

    }


    /**
     * 删除单个文件
     *
     * @param fileName：要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir：要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            // System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            // System.out.println("删除目录失败！");
            return false;
        }
        return true;
    }

    /**
     * 写文件
     *
     * @param in
     * @param out
     * @throws IOException
     */
    public static void writeFile(InputStream in, OutputStream out) throws IOException {
        int length;
        byte[] b = new byte[BUFFER_SIZE];
        while ((length = in.read(b)) != -1) {
            out.write(b, 0, length);
        }
    }

    /**
     * 创建目录
     *
     * @param outputDir
     * @param subDir
     */
    public static void createDirectory(String outputDir, String subDir) {
        File file = new File(outputDir);
        //子目录不为空
        if (!(subDir == null || subDir.trim().isEmpty())) {
            file = new File(outputDir + File.separator + subDir);
        }
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.mkdirs();
            log.info("mkdirs directory:{} ", file);
        }
    }

    /**
     * 删除Mac压缩再解压产生的 __MACOSX 文件夹和 .开头的其他文件
     *
     * @param filteredFile
     */
    public static boolean filterFile(File filteredFile, String csvFilePath) {
        boolean result = false;
        if (filteredFile != null) {
            File[] files = filteredFile.listFiles();
            for (File file : files) {
                if (file.getName().startsWith(".") || file.getName().endsWith(".meta") ||
                        (file.isDirectory() && file.getName().equals("__MACOSX"))) {
                    FileUtils.deleteQuietly(file);
                } else {
                    result = file.renameTo(new File(csvFilePath));
                    log.info("file rename result: {} csvFilePath: {} ", result, csvFilePath);
                }
            }
        }
        return result;
    }

    public static ArrayList<String> CSVToList(String csvFilePath) {
        ArrayList<String> csvData = new ArrayList<>();

        try {
            FileReader fileReader = new FileReader(csvFilePath);
            CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT);
            List<CSVRecord> csvRecords = csvParser.getRecords();
            boolean header = true;
            for (CSVRecord record : csvRecords) {
                if (header){
                    header = false;
                    continue;
                }
                String recordData = record.get(0);
                csvData.add(recordData);
            }
        } catch (IOException e) {
            log.info("CSVToList error", e);
        }
        return csvData;
    }
}